package com.hsjk.szwj.module.mp.controller.app;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.hsjk.szwj.framework.common.exception.ServiceException;
import com.hsjk.szwj.framework.common.exception.enums.GlobalErrorCodeConstants;
import com.hsjk.szwj.framework.common.pojo.CommonResult;
import com.hsjk.szwj.framework.security.core.annotations.PreAuthenticated;
import com.hsjk.szwj.framework.tenant.core.context.TenantContextHolder;
import com.hsjk.szwj.module.member.api.user.dto.MemberCreateReqDTO;
import com.hsjk.szwj.module.mp.controller.app.vo.AppAuthLoginRespVO;
import com.hsjk.szwj.module.mp.controller.app.vo.AppMiniLoginReqVO;
import com.hsjk.szwj.module.mp.controller.app.vo.AppMiniQrCodeCreateReqVO;
import com.hsjk.szwj.module.mp.dal.dataobject.MiniConfigDO;
import com.hsjk.szwj.module.mp.service.IMpService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.crypto.BadPaddingException;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.NoSuchPaddingException;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import java.io.UnsupportedEncodingException;
import java.security.InvalidAlgorithmParameterException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;

import static com.hsjk.szwj.framework.common.pojo.CommonResult.success;

/**
 * @author chenjiawei
 * @desc
 * @Date 2023/08/15 16:54
 **/
@Tag(name = "应用端 - 微信小程序授权相关接口")
@RestController
@RequestMapping("/wx-mini-app")
@Validated
@Slf4j
public class AppMiniAuthController {

    @Resource
    private IMpService mpService;

    @PostMapping("/login")
    public CommonResult<AppAuthLoginRespVO> loginByWxMini(@RequestBody @Valid AppMiniLoginReqVO reqVO) throws InvalidAlgorithmParameterException, NoSuchPaddingException, IllegalBlockSizeException, UnsupportedEncodingException, NoSuchAlgorithmException, BadPaddingException, InvalidKeyException {
        log.info("loginByWxMini:reqVO：" + JSONUtil.toJsonStr(reqVO));
        Long tenantId = TenantContextHolder.getTenantId();
        log.info("loginByWxMini:" + tenantId);
        MiniConfigDO miniConfig = mpService.getMiniByTenantId(tenantId);
        if (ObjectUtil.isNull(miniConfig)) {
            throw new ServiceException(GlobalErrorCodeConstants.BAD_REQUEST.getCode()
                    , "参数有误");
        }
        AppAuthLoginRespVO appAuthLoginRespVO = null;
        String url = "https://api.weixin.qq.com/sns/jscode2session?" +
                "appid=" + miniConfig.getAppId() +
                "&secret=" + miniConfig.getAppSecret() +
                "&js_code=" + reqVO.getCode() +
                "&grant_type=authorization_code";
        //利用spring原生http请求工具对接口进行请求
        String body = HttpUtil.createGet(url).execute().body();
        log.info("loginByWxMini:body:" + body);
        JSONObject bodyObject = JSONUtil.parseObj(body);
        String openId = bodyObject.getStr("openid");
        String sessionKey = bodyObject.getStr("session_key");
        String unionId = bodyObject.getStr("unionid");
        log.info("loginByWxMini:openid:" + openId);
        log.info("loginByWxMini:sessionKey:" + sessionKey);
        log.info("loginByWxMini:unionid:" + unionId);
        //解密
        String result = mpService.wxDecrypt(reqVO.getEncryptedData(), bodyObject, reqVO.getIv());
        JSONObject resultObject = JSONUtil.parseObj(result);
        log.info("loginByWxMini:resultObject" + resultObject);
        String nickName = resultObject.getStr("nickName");
        String headImgUrl = resultObject.getStr("avatarUrl");
        MemberCreateReqDTO reqDTO = new MemberCreateReqDTO();
        reqDTO.setNickname(nickName);
        reqDTO.setAvatar(headImgUrl);
        reqDTO.setUnionId(unionId);
        reqDTO.setTenantId(tenantId);
        reqDTO.setWxLiteOpenId(openId);
        if (ObjectUtil.isNotNull(reqVO.getUid())) {
            reqDTO.setInviterMemberId(Long.valueOf(reqVO.getUid()));
        }
        appAuthLoginRespVO = mpService.wxCallbackHandle(reqDTO);
        return success(appAuthLoginRespVO);
    }

    @PostMapping(value = "/create-qr-code")
    @Operation(summary = "生成小程序二维码")
    @PreAuthenticated
    public void createQrCode(@RequestBody @Valid AppMiniQrCodeCreateReqVO reqVO,
                             HttpServletResponse response) {
        mpService.createQrCode(reqVO, response);
    }
}
